package com.globalwave.common.web;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.globalwave.common.cache.CodeHelper;
import com.globalwave.common.scheduling.TaskScheduler;
import com.globalwave.common.service.InitServiceImpl;


/*******************************************************************************
 * 类说明: 初始化Servlet
 * <P>
 * 
 * @author 蒋勇
 *         <P>
 * @version 1.0 2005-3-2
 */
public class InitConfigServlet extends javax.servlet.http.HttpServlet {
	
	private Logger logger = Logger.getLogger(this.getClass()) ;
    /**
     * 刷新代码表doGet方式（集群环境需要在每台服务器上运行刷新）
     * 
     * @param request
     * @param response
     * @return 无
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doPost(request, response) ;
    }

    /**
     * 刷新代码表doPost方式（集群环境需要在每台服务器上运行刷新）
     * 
     * @param request
     * @param response
     * @return 无
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       
    }

    /**
     * <B>Describe：初始化方法，调用一些必要的过程 </B>
     * 
     * @param config
     */
    public void init(ServletConfig config) {
        try {
        	logger.info("init servlet start");
        	super.init(config);
        	
        	WebApplicationContext appContext = 
        		WebApplicationContextUtils.getWebApplicationContext(
    				config.getServletContext()) ;

        	CodeHelper.setWebConfig("realPath", config.getServletContext().getRealPath("/")) ;
        	CodeHelper.setWebConfig("appContext", appContext) ;
        	
        	InitServiceImpl initService = (InitServiceImpl)appContext.getBean("initService") ;
        	
        	initService.init() ;
        	
        	
        	//TaskScheduler.getInstance().initialize(appContext) ;
        	//TaskScheduler.getInstance().scheduleAll() ;
        } catch (Exception e) {
        	logger.error("Init Error:", e) ;
        }
    }

    /**
     * 应用停止时执行的任务
     * @author baolibing
     */
    public void destroy() {
    	TaskScheduler.getInstance().shutdown() ;
    	try {
			CodeHelper.setWebConfig("appContext", null) ;
		} catch (Exception e) {
        	logger.error("destroy Error:", e) ;
		}
    }
}